﻿using CKS2320.Common;
using CKS2320.Common.Model;
using CKS2320.Common.Utils;
using CKS2320.Domain.DBEntity;
using CKS2320.Repository.Interface;
using CKS2320.Service.Interface;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CKS2320.Service
{
    public class ShapeService : IShapeService
    {
        public IShapeRepository _shapeRepository;
        private readonly LogService _logService;
        public ShapeService(IShapeRepository shapeRepository, LogService logService)
        {
            _shapeRepository = shapeRepository;
            _logService = logService;
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <returns></returns>
        public ResultReturn Add(ShapeModel shapeModel)
        {
            _logService.LogOp10("保存参数：" + JsonConvert.SerializeObject(shapeModel) + "\r\n");
            try
            {
                float? HorizontalCamber = null;
                Shape shape = new()
                {
                    Id = Guid.NewGuid(),
                    StationCode = shapeModel.StationCode,
                    Heart1 = shapeModel.Heart1,
                    StartUpLoad = shapeModel.StartUpLoad,
                    Heart2 = shapeModel.Heart2,
                    EndUpLoad = shapeModel.EndUpLoad,
                    Result = shapeModel.Result,
                    PartCode = shapeModel.PartCode,
                    PartCodeResult = shapeModel.PartCodeResult,
                    PartCodeTrigger = shapeModel.PartCodeTrigger,
                    RunType = shapeModel.RunType,
                    CreatedTime = DateTime.Now,
                   // ModifiedTime = DateTime.Now
                };
                List<Detectiondetail> detailList = new();
                if (shapeModel.detaillist.Any())
                {
                    foreach (var item in shapeModel.detaillist)
                    {
                        detailList.Add(new Detectiondetail()
                        {
                            Id = Guid.NewGuid(),
                            ParentId = shape.Id,
                            DetectedType = item.DetectedType,
                            DetectedData = item.DetectedData,
                            Description = item.Description,
                            DetectedIndex = item.DetectedIndex,
                            DetectedTypeDisplay = item.DetectedTypeDisplay,
                            DetectedStatus = item.DetectedStatus,
                            DetectedTime = item.DetectedTime,
                            PartCode = item.PartCode,
                            Plcip = item.Plcip,
                            CreatedTime = DateTime.Now,
                            //ModifiedTime = DateTime.Now
                        });
                    }
                    HorizontalCamber = shapeModel.detaillist.Where(p => p.DetectedType == "BOW").FirstOrDefault()?.DetectedData;
                }
                Op10coredata op10CoreData = new Op10coredata() { 
                SerialNumber= shapeModel.PartCode,
                    TestTime = DateTime.Now,
                    Judge = shapeModel.Result.Value==true?"OK":"NG",
                    HorizontalCamber= HorizontalCamber,
                    Passageway = shapeModel.RunType,
                };
                _logService.LogOp10("客户核心数据保存：" + JsonConvert.SerializeObject(op10CoreData) + "\r\n");
                _shapeRepository.AddOP10(op10CoreData);
                return _shapeRepository.Add(shape, detailList);
            }
            catch (Exception ex)
            {
                _logService.LogOp10("保存失败：" + ex.ToString(), LogLevel.Error);
                return MessageInfoUtils.Fail(ex.Message);
            }
       
        }
        /// <summary>
        /// 是否存在
        /// </summary>
        /// <param name="partCode"></param>
        /// <returns></returns>
        public bool GetByPartCode(string partCode)
        {
            var shapeList = _shapeRepository.GetByPartCode(partCode);
            if (shapeList != null && shapeList.Any())
            {
                //若存在该code并结果为ok就不在继续进行，若结果是NG并大于1条也不在继续进行
                bool? partCodeResult = shapeList.OrderByDescending(p => p.CreatedTime).First().Result;
                if (partCodeResult == true)
                {
                    return true;
                }
                else
                {
                    if (shapeList.Where(p => p.Result == false).Count() > 1)
                    {
                        return true;
                    }
                }
            }
            return false;
        }
    }
}
